<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" />
    <title>title</title>
    <link rel="stylesheet" type="text/css" href="../../../css/api.css" />
    <link rel="stylesheet" type="text/css" href="../../../css/style.css" />
    <link rel="stylesheet" type="text/css" href="../../../css/aui.css" />
    <link rel="stylesheet" type="text/css" href="../../../icon/iconfont.css" />
    <style>
        .yue {
            padding: 2rem 0;
            text-align: center;
            border-bottom: 2px solid #eee
        }

        .enterVal {
            width: 8rem !important;
            border-bottom: 1px solid #EEE !important;
            display: inline-block !important;
            height: 1rem !important;
        }

        .enter_money p {
            padding: .5rem 0;
        }

        .logout {
            background-color: #D2984D;
            color: #FFF;
            width: 50%;
            margin: 2rem auto;
            ;
            border-radius: 3px;
            padding: .5rem 0;
            text-align: center;
        }

        .aui-radio:checked,
        .aui-radio.aui-checked,
        .aui-checkbox:checked,
        .aui-checkbox.aui-checked {
            background-color: #D2984D;
            border: solid 1px #D2984D;
        }

        header {
            padding: 1.6rem 0.8rem 0.5rem 0.8rem;
            position: fixed;
            width: 100%;
            background-color: #fff;
            z-index: 98;
            /*border-bottom: 1px solid #ccc*/
        }

        header span:nth-of-type(1) {
            font-size: 1rem
        }

        header span:nth-of-type(2) {
            font-size: 1rem
        }
    </style>
</head>

<body>
    <header>
        <span class="iconfont icon-fanhui" onClick="api.closeWin()"></span>
        <span>充值</span>
    </header>
    <div class="max-box" style="padding-top:4rem">
        <div class="yue">
            <p>当前余额</p>
            <p>
                <h1><label for="">&yen;&nbsp;</label><em id="currentYue"></em></h1></p>
        </div>
        <div class="enter_money yue" style="border:0;">
            <p>请输入充值金额</p>
            <p><label style="font-size: 2rem;color: #000;" for="">&yen;&nbsp;</label><input class="enterVal" type="number" name="money" value=""></p>
            <p class="logout" id="payPost">确认充值</p>
        </div>

        <div class="aui-list-item-inner" style="text-align:center;">
            <label><input class="aui-radio checked" type="radio" name="paytype" data-type="wxpay" checked>&nbsp;&nbsp;微信支付</label> &nbsp;&nbsp;&nbsp;
            <label><input class="aui-radio" type="radio" name="paytype" data-type="alipay">&nbsp;&nbsp;支付宝支付</label>
        </div>
    </div>
    <p class="yue" style="border:0;">充值说明：账户余额暂不支持退款</p>
</body>
<script type="text/javascript" src="../../../script/api.js"></script>
<script type="text/javascript" src="../../../script/dns.js"></script>
<script type="text/javascript" src="../../../script/jquery-3.3.1.js"></script>
<script type="text/javascript" src="../../../script/aui-toast.js"></script>
<script type="text/javascript" src="../../../lib/zepto.js"></script>
<script type="text/javascript">
    apiready = function() {
        $('#currentYue').html(api.pageParam.yue) //当前余额
    };
    var toast = new auiToast({})
    $("input[name='paytype']").each(function() {
        $(this).click(function() {
            $("input[name='paytype']").removeClass('checked');
            $(this).addClass('checked');
        });
    });

    $('#payPost').click(function() {
        var amount = $("input[name='money']").val();
        if (amount == '' || amount <= 0) {
            toast.fail({
                title: "请输入有效金额!",
                duration: 1500
            });
            return;
        } else {
            $("input[name='paytype']").each(function() {
                var status = $(this).data('type');
                if ($(this).hasClass('checked')) {
                    if (status == 'wxpay') {
                        serverWXPay(amount); //微信支付
                        return;
                    } else {
                        serverAlipay(amount); //支付宝支付
                        return;
                    }
                }
            })
        }
    });

    // 服务器支付宝预订单支付
    function serverAlipay(amount) {
        $.ajax({
            url: g_serverApi + 'v2/pre/pay',
            type: "POST",
            data: {
                'amount': amount,
                'type': 2,
            },
            dataType: 'json',
            beforeSend: function(request) {
                request.setRequestHeader("token", localStorage.getItem('token'));
            },
            success: function(res) {　　
                // console.log(JSON.stringify(res));　
                // 调取apicloud 支付功能
                AliPay(res);
            },
            error: function(err) {
              console.log(err);
                toast.fail({
                    title: "请重新发起充值",
                    duration: 2000
                });
                return;
            }
        });
    }
    // apiCloud支付宝支付
    function AliPay(serverData) {
        var aliPay = api.require('aliPay');

        aliPay.config({
            partner: serverData.data.partner,
            seller: serverData.data.seller,
            rsaPriKey: serverData.data.rsaPriKey,
            rsaPubKey: serverData.data.rsaPubKey,
            notifyURL: serverData.data.notify_url
        }, function(ret, err) {
            if (ret.status) {
                aliPay.pay({
                    subject: serverData.data.subject,
                    body: serverData.data.body,
                    amount: serverData.data.total_fee,
                    tradeNO: serverData.data.out_trade_no,
                }, function(ret, err) {
                  if(ret.code=="9000"){
                    toast.success({
                        title: "充值成功!",
                        duration: 2000
                    });
                    // 监听支付之后刷新个人中心
                    api.sendEvent({
                        name: "pay_reload"
                    })
                    setTimeout(function() {
                        api.closeWin()
                    }, 2000)
                  }else{
                    toast.fail({
                        title: "充值失败!",
                        duration: 2000
                    });
                  }
                });
            } else {
               api.alert({
                 title: '支付结果',
                 msg: err.msg,
                 buttons: ['确定']
               });
          }
        });


        // var obj = api.require('aliPay');
        // obj.config({
        //       partner: '2088431297871815',
        //       seller: '35965208@qq.com',
        //       rsaPriKey: 'MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCS0VckSzGLvdRUBg5LKNXtBW90ffZByZB9ujcH2gEIXxducZH9ctyTfvdTQFXeGIlTEJknB9ZxFPENCwuZUr/lSwhQJKdkFmHxjHbtFcHVrFmT/by2Dop5RUjcsZ9laJba87BDd/CuuHbGQzg/nSUBFIUUywxd7YUztOeKAXXiRGDdDe4buvPALTzU9h8iP0tHHHAB3Fw8cwveUosfp+tZ73bfxjkswb1TPc/p7MswNaHwlOrG/7Vj5n7dZyLTiVqzcROvZjd1pEYHiDXtjkEavJVarZTfiCLzQchwccnsipWq38iCPrqMYjDdbNdxj7mLWwPwjD+GfgroWdbLl0L/AgMBAAECggEAIQ+vFecw4wz+UWWDtn0dn2BH9u2elLX1KbrTRZtb/CydtCsy+uXwse43d7HXJEpWMjRcqKNlMNXMammAVSiDOfkpiBKY9zrrF1/QMBdkLN/A1EihREYF/MUTYU9GW6mvvuJ9YNQTiOTVKlRcyEZ03MdoKISI5mXkRv6H3VXy2969RXKx9ihWQA/oBtMwizidX9BhOxgGX7Obgb95PyCC1t4WlYL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ljhNhgPdyPuBV64bfQNN1PjbCzkIM6qRdKBoLPXmKKMiFYnkd6rAoprih3/PrQEB/VsW8OoM8fxn67UDYuyBTqA23MML9q1+ilIZwBC2AQ2UBVOrFXfFl75p6/B5KsiNG9zpgmLCUYuLkxpLQIDAQAB',
        //       notifyURL: serverData.data.notifyURL
        // }, function(ret, err) {
        //   console.log(JSON.stringify(ret));
        //     if (ret.status) {
        //         //配置成功，调用支付
        //         obj.pay({
        //             subject: serverData.data.subject,
        //             body: serverData.data.body,
        //             amount: serverData.data.amount,
        //             tradeNO: serverData.data.tradeNO,
        //         }, function(ret, err) {
        //             api.alert({
        //                 title: '支付结果',
        //                 msg: ret.msg,
        //                 buttons: ['确定']
        //             });
        //         });
        //     } else {
        //         api.alert({
        //             title: '支付结果',
        //             msg: err.msg,
        //             buttons: ['确定']
        //         });
        //     }
        // });
    }
</script>
<script type="text/javascript">
    // 服务器微信预订单支付
    function serverWXPay(amount) {
        $.ajax({
            url: g_serverApi + 'v2/pre/pay',
            type: "POST",
            data: {
                'amount': amount,
                'type': 1,
            },
            dataType: 'json',
            beforeSend: function(request) {
                request.setRequestHeader("token", localStorage.getItem('token'));
            },
            success: function(res) {　　
                // console.log(JSON.stringify(res));　
                // 调取apicloud 支付功能
                Wxpay(res);
            },
            error: function(err) {
                toast.fail({
                    title: "请重新发起充值",
                    duration: 2000
                });
                return;
            }
        });
    }
    // apiCloud微信支付
    function Wxpay(serverData) {
        var wxPay = api.require('wxPay');
        wxPay.config({
            apiKey: serverData.data.apiKey,
            mchId: serverData.data.mchId,
            partnerKey: serverData.data.partnerKey,
            notifyUrl: serverData.data.notifyUrl
        }, function(ret, err) {
            if (ret.status) {
                wxPay.pay({
                    description: serverData.data.description,
                    totalFee: serverData.data.totalFee,
                    tradeNo: serverData.data.tradeNo
                }, function(ret, err) {
                    // 用户正常行为点击了 返回商户 按钮
                    if (ret.status) {
                        toast.success({
                            title: "充值成功",
                            duration: 1500
                        });
                        // 监听支付之后刷新个人中心
                        api.sendEvent({
                            name: "pay_reload"
                        })
                        setTimeout(function() {
                            api.closeWin()
                        }, 2000)
                    } else {
                        toast.fail({
                            title: "充值失败",
                            duration: 2000
                        });
                        return;
                    }
                });
            } else {
                toast.success({
                    title: "充值失败",
                    duration: 1500
                });
                // 监听支付之后刷新个人中心
                api.sendEvent({
                    name: "pay_reload"
                })
                setTimeout(function() {
                    api.closeWin()
                }, 2000)

                return;
            }
            // 心跳查询该笔订单
            var orderStatus = setInterval(function() {
                getOrderStatus(serverData.data.tradeNo)
            }, 1000);
        });
    }
    // 查询订单支付状态
    function getOrderStatus(order_no) {
        $.ajax({
            url: g_serverApi + 'v2/pay/status?order=' + order_no,
            type: "GET",
            dataType: 'json',
            beforeSend: function(request) {
                request.setRequestHeader("token", localStorage.getItem('token'));
            },
            success: function(res) {　　
                // clearInterval(orderStatus)
                toast.success({
                    title: "充值成功",
                    duration: 1500
                });
                // 监听支付之后刷新个人中心
                api.sendEvent({
                    name: "pay_reload"
                })
                setTimeout(function() {
                    api.closeWin()
                }, 2000)
            },
            error: function(err) {
                toast.loading({
                    title: "请稍候",
                    duration: 2000
                }, function(ret) {

                });
                return;
            }
        });
    }
</script>

</html>
